package com.xinhe.web.util;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.codec.binary.Base64;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.Signature;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
@Slf4j
public class VechatPayV3Util {
    public static String getToken(String method, String canonicalUrl, String body, String merchantId, String certSerialNo, String keyPath) throws Exception {
        String signStr = "";
        String nonceStr = getRandomString(32);
        long timestamp = System.currentTimeMillis() / 1000L;
        if (StringUtils.isEmpty(body)) {
            body = "";
        }
        System.out.println("body的数据" + body);
        String message = buildMessage(method, canonicalUrl, timestamp, nonceStr, body);
        String signature = sign(message.getBytes("utf-8"), keyPath);
        signStr = "mchid=\"" + merchantId + "\",timestamp=\"" + timestamp + "\",nonce_str=\"" + nonceStr + "\",serial_no=\"" + certSerialNo + "\",signature=\"" + signature + "\"";
        return signStr;
    }
    public static String buildMessage(String method, String canonicalUrl, long timestamp, String nonceStr, String body) {
        return method + "\n" + canonicalUrl + "\n" + timestamp + "\n" + nonceStr + "\n" + body + "\n";
    }
    public static String sign(byte[] message, String keyPath) throws Exception {
        Signature sign = Signature.getInstance("SHA256withRSA");
        sign.initSign(getPrivateKey(keyPath));
        sign.update(message);
        return Base64.encodeBase64String(sign.sign());
    }
    public static PrivateKey getPrivateKey(String filename) throws IOException {
        log.error("签名 证书地址是 " + filename);
        String content = new String(Files.readAllBytes(Paths.get(filename, new String[0])), "utf-8");
        try {
            String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "").replace("-----END PRIVATE KEY-----", "").replaceAll("\\s+", "");

            KeyFactory kf = KeyFactory.getInstance("RSA");
            return kf.generatePrivate(new PKCS8EncodedKeySpec(
                    Base64.decodeBase64(privateKey)));
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("当前Java环境不支持RSA", e);
        } catch (InvalidKeySpecException e) {
            throw new RuntimeException("无效的密钥格式");
        }
    }

    public static String getRandomString(int length) {
        String base = "abcdefghijklmnopqrstuvwxyz0123456789";
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(base.length());
            sb.append(base.charAt(number));
        }
        return sb.toString();
    }
}
